<template>
    <div>
        <breadcrumb :routes="routes"></breadcrumb>
        <div class="goods-detail">
            <div class="dev-width">
                <div class="goods-show">
                    <div class="goods-pic">
                        <img class="goods-big-pic" v-if="!topImage.hasOwnProperty('fileUrl') && good.type=='01'" src="~/assets/images/zhuanli.png" />
                        <img class="goods-big-pic" v-else-if="!topImage.hasOwnProperty('fileUrl') && good.type=='02'" src="~/assets/images/tech.png" />
                        <img class="goods-big-pic" v-else :src="absUrl(topImage.fileUrl)" />
                        <my-carousel height="80px" width="400px" imgWidth="60px" imgHeight="60px" :items="getGoodImages" :total="5" @on-change="selectedItemChanged">
                        </my-carousel>
                    </div>
                    <div class="goods-msg">
                        <span class="title">
                            {{good.name}}
                            <span v-if='good.hits>0'>{{good.hits}}人浏览</span>
                            <span v-if='good.buyCount>0'>{{good.buyCount}}人意向购买</span>
                        </span>
                        <dl>
                            <dt>商品序号
                            </dt>
                            <dd>{{good.no}}</dd>
                        </dl>
                        <dl>
                            <dt>商品权属</dt>
                            <dd v-if="good.owner=='1'">自有</dd>
                            <dd v-if="good.owner=='2'">代理</dd>
                            <dd v-if="good.owner=='3'">代理</dd>
                        </dl>
                        <dl>
                            <dt>购买方式
                            </dt>
                            <dd>{{getPayMode()}}</dd>
                        </dl>
                        <dl>
                            <dt>价格
                                <span></span>
                            </dt>
                            <dd v-if='this.good.payMode==0'>
                                <b>¥ {{good.price|formatNumber}} 元</b>
                            </dd>
                            <dd v-else>
                                <b v-if='good.price==0 || good.price=="面议"'>面议</b>
                                <b v-else>¥ {{good.price|formatNumber}} 元</b>
                            </dd>
                        </dl>
                        <div class="goods-btns" v-if='good.status=="01"'>
                            <a class="btn-blue" @click='zixun'>咨询</a>
                            <a :class="['btn-orange',user!=null&&user.id==good.userId ? 'disabled':'']" :disabled='user!=null&&user.id==good.userId' v-if="good.payMode=='0'" @click="showBuyDialog">立即购买</a>
                            <a class="btn-blue" @click="applyAgentAsync" v-if="canProxy">代理</a>
                            <a :class="['btn-deepblue',user!=null&&user.id==good.userId ? 'disabled':'']" :disabled='user!=null&&user.id==good.userId' v-if="good.payMode=='1'" @click="showBuyDialog">意向购买</a>
                            <a class="btn-red" v-if='isOneself' @click="collection">{{collectionStatus?'收藏':'取消收藏'}}</a>
                        </div>
                    </div>
                </div>
                <div class="goods-detail-long">
                    <div class="shop-box">
                        <h3>店铺信息</h3>
                        <div v-for="(item,index) of good.shopInfoDtos" :key="index">
                            <div v-if="item.userId==good.userId">
                                <img v-if="!item.hasOwnProperty('logoUrl')" src="../../assets/images/default/dp_logo.png">
                                <img v-else :src="absUrl(item.logoUrl)" />
                                <h4>
                                    <span>{{item.name}}</span>
                                </h4>
                                <div>
                                    <span class="phone">电话</span>
                                    <span class="phoneNumber">{{item.contactPhone}}</span>
                                    <nuxt-link :to="{path:'/shop',query:{id:item.id}}">店铺首页</nuxt-link>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="goods-detail-main">
                        <Tabs type="card">
                            <TabPane label="商品详情" style="overflow:hidden">
                                <div v-html='good.description'></div>
                            </TabPane>
                            <TabPane label="商品摘要">
                                <pre class="pre">{{good.summary}}</pre>
                            </TabPane>
                            <TabPane label="详细参数">
                                <table class="goods-two" v-if="good.type=='01'">
                                    <tbody>
                                        <tr>
                                            <td class="label">商品类型</td>
                                            <td>专利</td>
                                            <td class="label">申请号</td>
                                            <td>{{good.patentApplyNo}}</td>
                                            <td class="label">所属行业</td>
                                            <td>暂缺</td>
                                        </tr>
                                        <tr>
                                            <td class="label">专利类型</td>
                                            <td>{{filterChildType(good.childType)}}</td>
                                            <td class="label">法律状态</td>
                                            <td>{{getPatentLawStatus()}}</td>
                                            <td class="label">IPC分类号</td>
                                            <td>{{good.patentIpcCode}}</td>
                                        </tr>
                                        <tr>
                                            <td class="label">交易方式</td>
                                            <td>{{getPayMode()}}</td>
                                            <td class="label">专利状态</td>
                                            <td>{{getPatentStatus()}}</td>
                                            <td class="label">授权号</td>
                                            <td>{{good.patentGrantNo}}</td>
                                        </tr>
                                        <tr>
                                            <td class="label" style="width:117px">高新技术领域分类</td>
                                            <td style="font-size:12px;width:180px;line-height:17px">{{getHightTechList()}}
                                            </td>
                                            <td class="label">信息有效期至</td>
                                            <td>{{good.patentPublishValidityTime |formatDate('yyyy-MM-dd') ||'长久有效' }}</td>
                                            <td class="label">授权日</td>
                                            <td>{{good.patentGrantDate}}</td>
                                        </tr>
                                    </tbody>
                                </table>
                                <table class="goods-two" v-if="good.type=='02'">
                                    <tbody>
                                        <tr>
                                            <td class="label">商品类型</td>
                                            <td>技术成果</td>
                                            <td class="label">项目阶段</td>
                                            <td>{{getAchievementStage(good.achievementStage)}}</td>
                                            <td class="label">技术领域</td>
                                            <td>{{filterChildType(good.childType)}}</td>
                                        </tr>
                                        <tr>
                                            <td class="label">专利号</td>
                                            <td>{{getGoodsAchievementPatentNo()}}</td>
                                            <td class="label">成果权属</td>
                                            <td v-if="good.achievementOwner=='1'">独占</td>
                                            <td v-if="good.achievementOwner=='2'">共有</td>
                                            <td class="label">知识产权状况</td>
                                            <td>{{getGoodsAchievementPatentType()}}</td>
                                        </tr>
                                        <tr>

                                            <td class="label" style="width:117px">高新技术领域分类</td>
                                            <td style="font-size: 12px;width: 180px;line-height:17px">
                                                {{getHightTechList()}}
                                            </td>
                                            <td class="label">交易方式</td>
                                            <td>{{getPayMode()}}</td>
                                            <td class="label">信息有效期至</td>
                                            <td>{{good.achievementPublishVilidTime|formatDate('yyyy-MM-dd') ||'长久有效' }}</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </TabPane>
                            <TabPane label="其他附件">
                                <div>
                                    <div v-for="(item,index) in getAttachments()" :key="index">
                                        <a :href="absUrl(item.fileUrl)" :download="item.fileName">{{item.fileName}}</a>
                                    </div>
                                </div>
                            </TabPane>
                        </Tabs>
                    </div>
                </div>
            </div>
        </div>
        <Modal class="confirm-dialog" v-model="loginVisible" width="360">
            <p slot="header" style="color:#f60;text-align:center">
            </p>
            <div style="text-align:center">
                <p> 抱歉，您没有登录无权访问该页面!</p>
                <nuxt-link :to="{path:'/login',query:{
                  callback:''
                }}" class="h_l">立即登录
                </nuxt-link>
            </div>
            <div slot="footer">
            </div>
        </Modal>
        <Modal class="confirm-dialog" v-model="realNameVisible" width="360">
            <p slot="header" style="color:#f60;text-align:center">
            </p>
            <div style="text-align:center">
                <p> 抱歉，您没有实名认证无权访问该页面!</p>
                <!--<a :href="businessBrowserUrl+'/realname'" class="h_l">立即实名认证</a>-->
            </div>
            <div slot="footer">
                <Button class="long" @click="operateClick">立即实名认证</Button>
            </div>
        </Modal>
        <Modal class="confirm-dialog" v-model="contactPhoneVisible" width="360">
            <p slot="header" style="color:#f60;text-align:center">
                联系方式
            </p>
            <div>
                <div v-for="(item,index) of good.shopInfoDtos" :key="index" style="padding:10px 30px;">
                    <h4 style="text-align: left;">
                        <span>店铺名称:{{item.name}}</span>
                    </h4>
                    <div style="text-align: left;">
                        <span class="phoneNumber">{{item.contactPhone?'联系电话:'+item.contactPhone:'未留联系电话,请联系平台'}}</span>
                    </div>
                </div>
            </div>
            <div slot="footer">
                <Button class="long" @click="contactPhoneVisible=false">关闭</Button>
            </div>
        </Modal>
        <Modal class="confirm-dialog" v-model="collectionVisible" :mask-closable="false" width="360">
            <p slot="header">
                确认{{collectionStatus?'收藏':'取消收藏'}}商品吗
            </p>
            <div slot='footer' style="width:100%;">
                <Button type="text" style="background: #F8F6F6; color: #666666;" @click='collectionVisible=false'>取消
                </Button>
                <Button type="text" @click='collectionConfirm'>确认</Button>
            </div>
        </Modal>
        <Modal class="confirm-dialog" v-model="dialogVisible" :title="buyForm.title">
            <Form class="p20" ref="buyForm" :model="buyForm" :label-width="80" :rules="rules">
                <FormItem v-if='good.payMode == 0' label="一口价金额">
                    <span class="priceA">￥ {{good.price}}</span>
                </FormItem>
                <FormItem v-else label="意向金额" prop="price">
                    <Input v-model="buyForm.price" placeholder="请输入价格"></Input>
                </FormItem>
                <FormItem>
                    <Checkbox v-model="buyForm.agreeProtocal">
                        <span class="check-word">同意平台
                            <a @click.stop.prevent="showProtocal">《交易规则》</a>条款</span>
                    </Checkbox>
                </FormItem>
            </Form>
            <div slot='footer'>
                <Button @click='dialogVisible=false'>取消</Button>
                <Button @click='buy'>确认</Button>
            </div>
        </Modal>
        <Modal class="confirm-dialog" v-model="isVisble" width="650" :style="{top:'82px'}" :mask-closable="false" :closable="false">
            <div slot="header">
                <strong>交易协议</strong>
            </div>
            <div>
                <div style="text-align:right;font-size:12px;margin-right:10px">
                    {{portocol.version}}发布于:{{portocol.createTime|formatDate('yyyy-MM-dd')}}
                </div>
                <div class="portal-content" v-html="portocol.content">
                </div>
            </div>
            <div slot="footer" style="display:block;text-align:center;padding:10px">
                <Button class="center" @click="isVisble=false">关闭</Button>
            </div>
        </Modal>

        <Modal class="confirm-dialog" v-model="agentSuccess" width="360" :mask-closable="false" :closable="false">
            <p slot="header" style="color:#f60;text-align:center">
            </p>
            <div>
                <div style="text-align:center;font-size: 14px">
                    您的代理申请已经提交，请等待商品发布者处理
                </div>
            </div>
            <div slot="footer">
                <Button class="long" @click="agentSuccess=false">确定</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
import portal from "~/net/portal"
import { searchCodes } from "~/constant/SearchCodes"
import { isNumber } from "~/constant/validform"
import { absUrl } from '~/utils/tool'
import breadcrumb from '~/components/Breadcrumb'
import myCarousel from '~/components/MyCarousel'
import { mapState } from 'vuex'
import config from "~/config"

export default {
    name: 'good',
    head() {
        return {
            title: '商品详情'
        }
    },
    data() {
        return {
            collectStatus: '',
            agentSuccess: false,
            contactPhoneVisible: false,
            collectionVisible: false,
            collectionStatus: true,
            isVisble: false,
            portocol: {
                content: '',
                createTime: '',
                version: ''
            },
            topImage: {},
            id: 0,
            codes: searchCodes,
            absUrl,
            good: {},
            phoneVisble: false,
            loginVisible: false,
            realNameVisible: false,
            dialogVisible: false,
            businessBrowserUrl: config.businessBrowserUrl,
            buyForm: {
                title: '',
                agreeProtocal: false,
                price: 0
            },
            rules: {
                price: isNumber('价格必须输入数字')
            }
        }
    },
    components: {
        breadcrumb,
        myCarousel,
    },
    computed: {
        ...mapState(['user', 'identities']),
        routes() {
            return [
                { name: '首页', path: '/' },
                { name: this.getGoodType() },
                { name: this.good.name }
            ]
        },

        getGoodImages() {
            if (this.good.hasOwnProperty('goodsFileDtos')) {
                let list = this.good.goodsFileDtos.filter(_ => {
                    return _.fileType == 3
                }).map((_, index) => {
                    return {
                        id: index,
                        src: _.fileUrl
                    }
                });
                return list;
            } else {
                return []
            }
        },
        canProxy() {
            return this.good.owner === '1' && this.identities.some(_ => _.type == '01');
        },
        isOneself() {
            if (this.user !== null && (this.good.userId !== null)) {
                return this.user.id !== this.good.userId
            } else {
                return true
            }
        },
    },
    created() {
        if (typeof (this.$route.query.id) != 'undefined')
            this.id = this.$route.query.id;
        this.goodsId = this.$route.query.id;
    },
    async asyncData(context) {
        let [resp1, resp2] = await Promise.all([
            portal.getGoodsInfo({
                query: {
                    id: context.query["id"],
                    isPortal: true
                },
                client: context.req
            }),
            portal.judgeCollected({
                query: {
                    id: context.query["id"],
                    type: '00'
                },
                client: context.req
            })
        ]);
        let data1 = resp1.data;
        let data2 = resp2.data;
        return {
            good: data1,
            topImage: data1.hasOwnProperty('goodsFileDtos') ? data1.goodsFileDtos[0] : {},
            collectionStatus: (data2 === '01') ? true : false,
            collectStatus: (data2 === '01') ? '00' : ''
        }
    },

    methods: {
        operateClick() {
            location.href = this.businessBrowserUrl + '/realname';
        },
        collection() {
            if (this.user == null) {
                this.loginVisible = true;
                return;
            }
            if (this.user !== null) {
                this.collectionVisible = true;
                return;
            }
        },
        //收藏  传收藏id
        collectionConfirm(collectionStatus) {
            portal.setCollectStatus({
                query: {
                    id: this.goodsId,
                    type: '00',
                    status: this.collectStatus
                },
            }).then((res) => {
                let { code, message } = res;
                if (code === '0000') {

                    if (this.collectStatus === '00') {
                        this.collectStatus = '01'
                        this.collectionVisible = false;
                        this.collectionStatus = false
                        this.$Message.success('收藏成功');
                    } else {
                        this.collectStatus = '00'
                        this.collectionVisible = false;
                        this.collectionStatus = true
                        this.$Message.success('已取消收藏');
                    }

                } else {
                    this.$Message.error(message);
                }
            })
        },
        selectedItemChanged(item) {
            this.topImage = {
                fileUrl: item.src
            }
        },

        showBuyDialog() {
            if (this.user == null) {
                this.loginVisible = true;
            } else {
                this.dialogVisible = true;
                if (this.good.payMode == 0) {
                    this.buyForm.title = '立即购买'
                } else {
                    this.buyForm.title = '意向购买'
                }
            }
        },
        showProtocal() {
            this.getProtocolAsync();
        },
        buy() {
            let params = {};
            if (this.good.payMode == 0) {
                if (!this.buyForm.agreeProtocal) {
                    this.$Message.warning('同意平台《交易规则》条款方可购买');
                    return;
                }
                params = {
                    status: '04',
                    goodId: this.good.id
                };
                this.handlePurchaseAsync(params);
            } else {
                if (this.buyForm.price < 0) {
                    this.$Message.warning('金额不能为负数');
                    return;
                }
                if (this.buyForm.price >= 10000000000000) {
                    this.$Message.warning('只能填入小于10,000,000,000,000的数字');
                    return;
                }
                this.$refs.buyForm.validate(valid => {
                    if (valid) {
                        if (!this.buyForm.agreeProtocal) {
                            this.$Message.warning('同意平台《交易规则》条款方可购买');
                            return;
                        }
                        params = {
                            status: '01',
                            goodId: this.good.id,
                            price: this.buyForm.price
                        };
                        this.handlePurchaseAsync(params);
                    }
                })
            }
        },
        getGoodType() {
            if (this.good.type === "01")
                return "专利";
            return "技术成果"
        },
        getPayMode() {
            if (this.good.payMode === '0')
                return '一口价';
            else
                return '意向购买'
        },
        getPatentLawStatus() {
            let status = '';
            switch (this.good.patentLawStatus) {
                case '1':
                    status = "审中";
                    break;
                case '2':
                    status = "有权";
                    break;
                case '3':
                    status = "无权";
                    break;
                default:
                    break;
            }
            return status
        },
        filterChildType(childType) {
            if (childType == undefined) {
                return '';
            } else {
                if (childType.startsWith("01")) {
                    return this.codes[1].childs.find(_ => _.code == childType).name;
                } else if (childType.startsWith("02")) {
                    return this.codes[2].childs.find(_ => _.code == childType).name;
                } else return "";
            }
        },
        getPatentStatus() {
            let status = '';
            switch (this.good.patentStatus) {
                case '1':
                    status = "申请中";
                    break;
                case '2':
                    status = "已公开";
                    break;
                case '3':
                    status = "已授权";
                    break;
                default:
                    break;
            }
            return status;

        },
        getHightTechList() {
            if (this.good.type === "01") {
                if (typeof (this.good.goodsPatentHighTechDtos) !== 'undefined')
                    return this.good.goodsPatentHighTechDtos.map(_ => {
                        return _.emergingName
                    }).join(" ")
            } else {
                if (typeof (this.good.goodsAchievementHighTechDtos) !== 'undefined')
                    return this.good.goodsAchievementHighTechDtos.map(_ => {
                        return _.achievementEmergingName
                    }).join(" ")
            }

        },
        getAchievementStage(index) {
            return ["研制", "试生产", "小批量生产", "批量生产", "其他"][index - 1]
        },
        getGoodsAchievementPatentNo() {
            if (this.good.hasOwnProperty('goodsAchievementPatentDtos')) {
                return this.good.goodsAchievementPatentDtos[0].achievementNo
            } else
                return ''
        },
        getGoodsAchievementPatentType() {
            if (this.good.hasOwnProperty('goodsAchievementPatentDtos')) {
                return this.good.goodsAchievementPatentDtos[0].achievementType
            } else
                return ''
        },
        getTransactionMode() {
            let status = '';
            switch (this.good.transactionMode) {
                case '00':
                    status = '股权投资';
                    break;
                case '01':
                    status = '技术转让';
                    break;
                case '02':
                    status = '许可使用';
                    break;
                case '03':
                    status = '合作开发';
                    break;
                case '04':
                    status = '合作兴办新企业';
                    break;
                case '05':
                    status = '其他';
                    break;
                default:
                    break;
            }
            return status;
        },
        getAttachments() {
            if (this.good.hasOwnProperty('goodsFileDtos')) {
                return this.good.goodsFileDtos.filter(_ => _.fileType == 1)
            } else {
                return []
            }
        },
        zixun() {
            if (this.user == null) {
                this.loginVisible = true;
                return;
            }
            if (this.user.userStatus != 2 && this.user.userStatus != 5) {
                this.realNameVisible = true;
                return;
            }
            if (this.contactPhoneVisible !== true) {
                portal.getPhoneByGoodsId({
                    query: {
                        goodsId: this.good.id
                    }
                }).then(res => {
                    this.good.shopInfoDtos.forEach((item, index) => {
                        item.contactPhone = res.data[index]
                    })
                    this.phoneVisble = true;
                    // this.$Message.success('请查看店铺联系人手机')
                    this.contactPhoneVisible = true;
                })
            }
        },
        async applyAgentAsync() {
            let { code, data, message } = await
                portal.applyAgent({
                    body: this.good.id
                });
            if (code === '0000') {
                this.agentSuccess = true;
            }
            if (code === '131147') {
                this.$Message.warning('您必须要有一个自己店铺才能代理商品')
            }
        },
        async handlePurchaseAsync(params) {
            let { code } = await
                portal.handlePurchase({
                    query: params
                });
            if (code === '0000') {
                this.$Message.success('购买确认成功');
                this.dialogVisible = false;
            } else {
                this.$Message.error(message);
            }
        },
        async getProtocolAsync() {
            let resp = await
                portal.getProtocol({
                    query: {
                        type: '06'
                    }
                })
            if (resp.code == '0000') {
                this.isVisble = true
                this.portocol = resp.data;
            }
        }
    }
}
</script>
<style>
@import "~/assets/styles/goods-detail.css";
</style>